package	birdry.ui	{
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import com.greensock.TweenLite;
	import birdry.utils.ArrayUtil;
	
	public class CircleSorting extends EventDispatcher	{
		
		public static const CIRCLE_MOVE:String = "circle_move";
		
		var i:uint;
		var divisionRadian:Number;
		public var radiusX:uint = 200;
		public var radiusY:uint = 200;
		public var direct:String = "left";
		var _position:Number = 0;
		var total:uint;
		var circleArray:Array;
		public var saveNum:int = 0;
		public var startNum:uint = 0;
		
		public function CircleSorting(circleArray:Array): void	{
			this.circleArray = circleArray;
			this.total = circleArray.length;
			this.divisionRadian = 2 * Math.PI/total;
		}
		
		
		public function sort(): void	{
			var order:uint;
			for (i = 0; i < total; ++i)		{
				order = (direct == "left") ? i : total - i;
				circleArray[i].x = radiusX * Math.sin(divisionRadian * ((order + startNum) - position));
				circleArray[i].y = radiusY * Math.cos(divisionRadian * ((order + startNum) - position));
				//circleArray[i].rotation = (Math.atan2(0-circleArray[i].y, 0-circleArray[i].x)*(180/Math.PI))-90;
			}
		}
		
		
		public function move(num:int): void	{
			saveNum += num;
			if (saveNum < 0)	{
				saveNum = total - 1;
			}	else if ( saveNum > total - 1)	{
				saveNum = 0;
			}
			moveTo(saveNum)
		}
		
		public function moveTo(num:int): void	{
			position = position % total;
			var order:uint  = (direct == "left") ? num : total - num;
			if ( Math.abs(position - order) > total / 2)	{
				position = (position - order > 0)	?	position -= total	:	position += total;
			}
			saveNum = order;
			TweenLite.to(this, 0.4, { position:order } );
			dispatchEvent(new Event(CircleSorting.CIRCLE_MOVE));
		}
		
		public function get position(): Number	{
			return _position;
		}
		
		public function set position( value: Number ): void	{
			_position = value;
			sort();
		}
	}	// class
}	// package